package com.mlink.ai.chat.utils

import android.content.Context
import androidx.work.*
import com.mlink.ai.chat.firebase.ChatRemoteConfig
import java.util.concurrent.TimeUnit

class RemoteConfigWorker(val context: Context, params: WorkerParameters) : Worker(context, params) {

    override fun doWork(): Result {
        return try {
            start(context)
            Result.success()
        } catch (e: Exception) {
            Result.failure()
        }
    }

    companion object {
        private const val REMOTE_CONFIG_TAG = "RemoteConfigWorker"

        fun start(context: Context) {
            try {
                ChatRemoteConfig().fetchConfig()
                // 每一小时执行一次任务
                val request = OneTimeWorkRequest.Builder(RemoteConfigWorker::class.java)
                    .setInitialDelay(1, TimeUnit.HOURS)
                    .addTag(REMOTE_CONFIG_TAG)
                    .build()
                WorkManager.getInstance(context).enqueueUniqueWork(
                    REMOTE_CONFIG_TAG,
                    ExistingWorkPolicy.REPLACE,
                    request
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }
}
